package cn.hinglo.permission.service.impl;

import cn.hinglo.common.cache.SelfCacheKit;
import cn.hinglo.common.constant.SystemConstant;
import cn.hinglo.permission.model.Permission;
import cn.hinglo.permission.service.UserPermission;
import com.jfinal.plugin.activerecord.Db;

import java.util.ArrayList;
import java.util.List;

/**
 * @createTime: 2018/12/29
 * @author: HingLo
 * @description: 用户权限具体实现, 对外提供的接口
 */
public class UserPermissionImpl implements UserPermission {

    /***
     * 通过用户Id来获取权限集合,与权限校验
     * @param userId 用户的Id
     * @return 返回权限集合
     */
    @Override
    public List<String> findPermissionByUserId(String userId) {
        //从缓存中获取权限
        List<String> list = SelfCacheKit.get(SystemConstant.PERMISSION, userId);
        if (list == null) {
            list = new ArrayList<>();
            //查询全部权限
            String sql = Db.getSql("user.Login-permission");
            List<Permission> permissionList = Permission.dao.find(sql, userId);
            //遍历权限URL,并添加到List中
            for (Permission permission : permissionList) {
                list.add(permission.getUrl());
            }
            //缓存权限URL
            SelfCacheKit.put(SystemConstant.PERMISSION, userId, list);
        }
        return list;
    }

    /***
     * 判断用户是否拥有该权限
     * @param userId 用户
     * @param url 权限的url
     * @return 返回结果
     */
    @Override
    public boolean hasPermission(String userId, String url) {
        List<String> list = findPermissionByUserId(userId);
        return list != null && list.contains(url);
    }
}
